package com.xmg.p2p.base.controller;

import com.xmg.p2p.base.domain.UserFile;
import com.xmg.p2p.base.service.ISysDictService;
import com.xmg.p2p.base.service.IUserFileService;
import com.xmg.p2p.base.util.JSONResult;
import com.xmg.p2p.base.util.UploadUtil;
import com.xmg.p2p.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class UserFilesController {
    @Autowired
    private IUserFileService userFileService;
    @Autowired
    private ServletContext servletContext;
    @Autowired
    private ISysDictService sysDictService;

    @RequestMapping("userFile")
    public String userFile(Model model, HttpServletRequest request) {
        Long id = UserContext.getCurrent().getId();
        List<UserFile> userFiles = userFileService.listByHasType(id, false);
        if (userFiles.size() > 0) {
            model.addAttribute("fileTypes", sysDictService.selectByParentSn("userFileType"));
            model.addAttribute("userFiles", userFiles);
            return "userFiles_commit";
        }
        model.addAttribute("sessionid", request.getSession().getId());
        userFiles = userFileService.listByHasType(id, true);
        model.addAttribute("userFiles", userFiles);
        return "userFiles";
    }

    @ResponseBody
    @RequestMapping("userFileUpload")
    public void uploadFileUpload(MultipartFile file) {
        String basePath = servletContext.getRealPath("/upload");
        String fileName = UploadUtil.upload(file, basePath);
        fileName = "/upload" + "/" + fileName;
        userFileService.apply(fileName);
    }
    @ResponseBody
    @RequestMapping("userFile_selectType")
    public JSONResult selectType(Long[] fileType, Long[] id) {
        if (fileType != null && id != null && fileType.length == id.length) {
            userFileService.batchUpdateFileType(id, fileType);
        }
        return new JSONResult();
    }
}
